package org.h.apiinterface.filter;
import org.h.apiinterface.model.reslut.Result;
import org.h.apiinterface.service.InterfaceInfoService;
import org.h.apiinterface.service.UserService;
import org.h.apiinterface.util.JacksonUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Order(1)
@Component
public class WebVisitFilter implements Filter {

    @Resource
    private InterfaceInfoService interfaceInfoService;
    @Resource
    private UserService userService;
    final private List<String> list = Arrays.asList("/user/login","/user/register","/pas");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String requestURI = httpServletRequest.getRequestURI();
        if (userService.isPermission(httpServletRequest.getHeader("accessKey"), httpServletRequest.getHeader("secretKey"))){
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            System.out.println("拦截起执行了-----");
            //是否已登录
            HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
            httpServletResponse.setContentType("application/json; charset=UTF-8");
            String res = JacksonUtils.objectToJson(Result.faile("认证失败 请检查 accessKey secretKey 是否正确"));
            httpServletResponse.getWriter().write(res);
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }



}
